package org.wk.logger.service;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.wk.core.common.view.PageVo;
import org.wk.logger.dao.LogDao;
import org.wk.logger.domain.LogEntity;
import org.wk.logger.view.LogVo;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class LogServiceImpl implements LogService {

    @Autowired
    private LogDao logDao;


    @Override
    public void insert(LogEntity logEntity) {
        logDao.save(logEntity);
    }

    @Override
    public PageVo findLogListPage(Map<String, Object> params) {
        String noticeTitle = (String)params.get("noticeTitle");
        String temp = (String)params.get("page");
        Integer pageNo = temp==null?0:Integer.parseInt(temp)-1;
        temp = (String) params.get("limit");
        Integer pageSize = temp==null?10:Integer.parseInt(temp);
        Page<LogEntity> page = logDao.findAll(PageRequest.of(pageNo, pageSize, new Sort(Sort.Direction.DESC, "createTime")));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<LogVo> result = new ArrayList<>();
        for (LogEntity log: page.getContent() ) {
            LogVo logVo = new LogVo();
            BeanUtils.copyProperties(log,logVo);
            logVo.setCreateTime(sdf.format(log.getCreateTime()));
            result.add(logVo);
        }
        PageVo pageVo = new PageVo<LogVo>();
        pageVo.setTotal(page.getTotalElements());
        pageVo.setPageNo(++pageNo);
        pageVo.setPageSize(pageSize);
        pageVo.setResult(result);
        pageVo.setTotalPages(page.getTotalPages());
        return pageVo;
    }
}
